﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using CommunitySystem.BO;
using System.Data.SqlClient;

namespace CommunitySystem.Web.Service
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "RightService" in code, svc and config file together.
    public class RightService : IRightService
    {
        public void DoWork()
        {
        }


        public bool UpdatePermission(int OrgID, System.Collections.ObjectModel.ObservableCollection<Model.PermissionBase> Permissions)
        {
            using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["JinYang"].ConnectionString))
            {
                SqlTransaction transaction = null;
                try
                {
                    conn.Open();
                    transaction = conn.BeginTransaction();
                    string sql = "delete PermissionBase where OrgBaseID=" + OrgID;
                    SqlCommand cmmd = new SqlCommand(sql, conn, transaction);
                    cmmd.ExecuteNonQuery();

                    List<SqlParameter> list = null;
                    StringBuilder  sb = new StringBuilder( @"INSERT INTO [PermissionBase]
           ([OrgBaseID]
           ,[VerbBaseGuid]
           ,[VerbBaseCode])
");
                    string values = "   select {0} , '{1}', '{2}'   ";
                    foreach (var p in Permissions)
                    {
                        sb.Append(string.Format(values, p.OrgBaseID, p.VerbBaseGuid, p.VerbBaseCode));
                        if (Permissions.LastOrDefault() == p)
                        {
                            sb.Append(";");
                        }
                        else
                        {
                            sb.Append(" union  ");
                        }
                    }
                    cmmd.CommandText = sb.ToString();
                   
                    cmmd.ExecuteNonQuery();
                    transaction.Commit();

                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    return false;
                }
            }
            return true;
        }

        public System.Collections.ObjectModel.ObservableCollection<Model.PermissionBase> GetPermission(string condition)
        {
            return AccessHelper.GetInstance().GetEnity<Model.PermissionBase>(condition, "PermissionBase");
        }
    }
}
